package com.oscar.ehome.view.pageview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.joanzapata.pdfview.PDFView;
import com.joanzapata.pdfview.listener.OnDrawListener;
import com.joanzapata.pdfview.listener.OnLoadCompleteListener;
import com.joanzapata.pdfview.listener.OnPageChangeListener;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.base.activity.BasesPdf;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.SystemBarTintManager;
import com.oscar.ehome.utils.util.ToastUtil;


import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/7/10
 * pdf播放
 */

public class PdfActivity extends BasesPdf implements OnPageChangeListener
        , OnLoadCompleteListener, OnDrawListener {

    @BindView(R.id.home_tv_num)
    TextView title_tv_right;
    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * PDF   view
     */
    @BindView(R.id.pdfView)
    PDFView pdfView;
    /*
    PDF全屏按钮
     */
    @BindView(R.id.pdfquanping)
    ImageView pdfquanping;
    @BindView(R.id.hengpingfanhui)
    ImageView pdfshuping;
    @BindView(R.id.yincangzhuangtai)
    FrameLayout pdfzhuangtai;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    SystemBarTintManager tintManager = null;
    String url = "";
    String fileName = "", open = "";//文件名
    int pageNumber = 1;
    int hengshu = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pdf);
        setBaseBackground(PdfActivity.this);
        ButterKnife.bind(this);
        setColor();
        url = getIntent().getStringExtra("url");
        open = getIntent().getStringExtra("open");
        fileName = getIntent().getStringExtra("fileName");
        if (isScreenOriatationPortrait(PdfActivity.this)) {

            basetitleBar.setVisibility(View.VISIBLE);
        } else {

            basetitleBar.setVisibility(View.GONE);
        }
        if (url.equals("1")) {//本地阅读
            initView();
        } else {//在线阅读
            titleImgBack.setImageResource(R.mipmap.fanhui);
            titleImgBack.setVisibility(View.VISIBLE);
            titleTopbar.setText("PDF");
            displayFromFile1(url, fileName);
            showLoading();
        }

    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    /**
     * 设置颜色
     */
    public void setColor() {

        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(PdfActivity.this).getSystemConfig().getColor()));
//        TintManager.setTint(roundProgressBar, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    /**
     * 获取打开网络的pdf文件
     *
     * @param fileUrl
     * @param fileName
     */
    private void displayFromFile1(String fileUrl, String fileName) {
        pdfView.fileFromLocalStorage(this, this, this, fileUrl, pageNumber, fileName);   //设置pdf文件地址

    }

    String fileAbsolutePath;

    /**
     * 打开本地PDF
     */
    public void initView() {
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);
        titleTopbar.setText("PDF");
        if (open!=null&&open.equals("ture")) {
            fileAbsolutePath = CommonUtils.getSDCardRootPath() + C.video + fileName;
            title_tv_right.setVisibility(View.VISIBLE);
            title_tv_right.setText("发送");
            titleImgBack.setVisibility(View.VISIBLE);
            titleImgBack.setImageResource(R.mipmap.fanhui);
        } else {
            fileAbsolutePath = CommonUtils.getSDCardRootPath(PdfActivity.this) + C.video + fileName;
            title_tv_right.setVisibility(View.GONE);
            titleImgBack.setVisibility(View.VISIBLE);
            titleImgBack.setImageResource(R.mipmap.fanhui);
        }

        if (GetVideoFileName(fileAbsolutePath)) {
            File dstDiretory = new File(fileAbsolutePath);
            displayFromFile(dstDiretory);
        }
    }

    /**
     * 查询内存卡是否下载该文件
     *
     * @param fileAbsolutePath
     * @return
     */
    public boolean GetVideoFileName(String fileAbsolutePath) {
        File dstDiretory = new File(fileAbsolutePath);
        if (dstDiretory.exists()) {// 目标目录不存在
            return true;
        }
        return false;
    }


    @OnClick({R.id.title_layout_left, R.id.pdfView, R.id.pdfquanping, R.id.hengpingfanhui,R.id.home_tv_num})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_tv_num:
                if (title_tv_right.getText().equals("发送")) {

                    if (GetVideoFileName(fileAbsolutePath)) {
                        new PopupWindows(PdfActivity.this, title_tv_right);
                    } else {
                        ToastUtil.show(PdfActivity.this, "未查找到该文件。");
                    }


                } else {

                }
                break;
            case R.id.title_layout_left:
                finish();
                break;
            case R.id.pdfView:
                break;
            case R.id.pdfquanping:
                pdfzhuangtai.setSystemUiVisibility(View.INVISIBLE);
                basetitleBar.setVisibility(View.GONE);
                tintManager.setStatusBarTintResource(R.color.transparent);
                PdfActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                pdfquanping.setVisibility(View.GONE);
                pdfshuping.setVisibility(View.VISIBLE);


                break;
            case R.id.hengpingfanhui:
                pdfzhuangtai.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                pdfquanping.setVisibility(View.VISIBLE);
                basetitleBar.setVisibility(View.VISIBLE);
                pdfshuping.setVisibility(View.GONE);
                tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(PdfActivity.this).getSystemConfig().getColor()));
                PdfActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


                break;


        }
    }

    private void displayFromFile(File file) {
        pdfView.fromFile(file)   //设置pdf文件地址
                .defaultPage(pageNumber)         //设置默认显示第1页
                .onPageChange(this)     //设置翻页监听
                .onLoad(this)           //设置加载监听
                .onDraw(this)            //绘图监听
                .showMinimap(false)     //pdf放大的时候，是否在屏幕的右上角生成小地图
                .swipeVertical(false)  //pdf文档翻页是否是垂直翻页，默认是左右滑动翻页
                .enableSwipe(true)   //是否允许翻页，默认是允许翻
                .load();
    }

    /**
     * 翻页回调
     *
     * @param page
     * @param pageCount
     */
    public void onPageChanged(int page, int pageCount) {
//        Toast.makeText(PdfActivity.this, "page= " + page +
//                " pageCount= " + pageCount, Toast.LENGTH_SHORT).show();
    }

    /**
     * 加载完成回调
     *
     * @param nbPages 总共的页数
     */
    public void loadComplete(int nbPages) {
        dismissLoading();
        // Toast.makeText(PdfActivity.this, "加载完成", Toast.LENGTH_SHORT).show();
    }

    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {
        // Toast.makeText( MainActivity.this ,  "pageWidth= " + pageWidth + "
        // pageHeight= " + pageHeight + " displayedPage="  + displayedPage , Toast.LENGTH_SHORT).show();
    }

    public static boolean isScreenOriatationPortrait(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    public void setBaseBackground(Activity act) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            CommonUtils.setTranslucentStatus(true, act);
            tintManager = new SystemBarTintManager(act);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(PdfActivity.this).getSystemConfig().getColor()));
        }
    }
    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            View view = View.inflate(mContext, R.layout.fenxiangbuju, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_qq);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_center);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    File f = new File(fileAbsolutePath);
                    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    sendIntent.setType("*/*");
                    sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");//微信朋友
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qqfav.widget.QfavJumpActivity");//保存到QQ收藏
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qlink.QlinkShareJumpActivity");//QQ面对面快传
//          sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.qfileJumpActivity");//传给我的电脑
                    //sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");//QQ好友或QQ群
//          sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");//微信朋友圈，仅支持分享图片
                    startActivity(sendIntent);


                    dismiss();

                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);

                    File f = new File(fileAbsolutePath);
                    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    sendIntent.setType("*/*");
                    // sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");//微信朋友
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qqfav.widget.QfavJumpActivity");//保存到QQ收藏
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qlink.QlinkShareJumpActivity");//QQ面对面快传
//          sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.qfileJumpActivity");//传给我的电脑
                    sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");//QQ好友或QQ群
//          sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");//微信朋友圈，仅支持分享图片
                    startActivity(sendIntent );


                    dismiss();

                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }
}
